package cn.etynit.org.service.impl;

import cn.etynit.basic.config.BussinessException;
import cn.etynit.basic.util.BaiduAuditUtils;
import cn.etynit.org.domain.Employee;
import cn.etynit.org.domain.Shop;
import cn.etynit.org.domain.ShopAuditLog;
import cn.etynit.org.enu.ShopStateEum;
import cn.etynit.org.mapper.EmployeeMapper;
import cn.etynit.org.mapper.ShopAuditLogMapper;
import cn.etynit.org.mapper.ShopMapper;
import cn.etynit.org.service.IShopService;
import cn.etynit.basic.service.impl.BaseServiceImpl;
import cn.etynit.org.vo.ShopEchartsVo;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author etynit
 * @since 2022-10-15
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopAuditLogMapper auditLogMapper;

    @Autowired
    private JavaMailSender sender;

    // 店铺入驻
    @Override
    public void settlement(Shop shop) {
        // 店铺对象获取管理员对象
        Employee admin = shop.getAdmin();
        // 通过了校验方法获取到的员工对象
        Employee employee = this.verify(shop, admin);
        // 存入数据了
        // 添加shop表
        shopMapper.add(shop);
        // 通过各种条件校验得到的对象如果是空的，则将前台传递的admin对象赋值给它
        if(null == employee){
            // 添加emp
            employee = admin;
            employeeMapper.add(employee);
        }
        // 修改员工的的shopId以及修改员工信息
        employee.setShopId(shop.getId());
        employeeMapper.update(employee);
        // 修改shop表的adminId
        // 创建一个shop对象
        Shop uptShop = new Shop();
        // 前端获取的
        uptShop.setId(shop.getId());
        uptShop.setAdminId(employee.getId());
        shopMapper.update(uptShop);
    }

    /**
     * 店铺审核通过接口
     * @param auditLog
     */
    @Override
    public void auditPass(ShopAuditLog auditLog) {
        // 判断参数
        // 判断备注是否为空
        if (StringUtils.isBlank(auditLog.getNote())){
           throw  new SecurityException("备注不能为空");
        }
        // 判断店铺id是否为空
        // 修改店铺审核通过的状态为 审核通过、已激活
        // 创建一个shop对象
        Shop shop = new Shop();
        // 前端传递的值赋值到shopId中
        shop.setId(auditLog.getShopId());
        // 更改State店铺状态为1，审核通过
        shop.setState(1);
        // 将店铺状态更新
        shopMapper.update(shop);
        // 添加审核人id
        auditLog.setAuditId(123L);
        // 添加店铺日志
        auditLogMapper.add(auditLog);
        // 发送邮件
        // 发送邮件
        // 1.创建复杂邮件对象
        MimeMessage mimeMessage = sender.createMimeMessage();
        // 2.发送复杂邮件的工具类
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("wang155775@qq.com");
            helper.setSubject("宠物直接审核结果通知");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>恭喜您审核您审核通过，点击下方链接激活店铺</h1>"+
                    "http://localhost:8080/shop/active/"+auditLog.getShopId(),true);
            helper.setTo("wang155775@qq.com");
        } catch (Exception e){
            throw new BussinessException("发送邮件错误！");
        }
        sender.send(mimeMessage);
    }

    // 店铺激活
    @Override
    public void active(Long id) {
        Shop shop = new Shop();
        shop.setId(id);
        shop.setState(2);
        shopMapper.update(shop);
    }

    @Override
    public Map<String, Object> echarts() {
        Map<String,Object> result = new HashMap<>();
        List<ShopEchartsVo> vo= shopMapper.echarts();
        List<Integer> x = vo.stream().map(ShopEchartsVo::getState).collect(Collectors.toList());
//        List<Integer> xT = new ArrayList<>();
//        for (ShopEchartsVo echartsVo : vo) {
//            xT.add(echartsVo.getState());
//        }
        List<Integer> y = vo.stream().map(ShopEchartsVo::getCount).collect(Collectors.toList());
        List<String> realX = new ArrayList<>();
        for (Integer xTemp : x) {
            String stateName = ShopStateEum.getNameByCode(xTemp);
            realX.add(stateName);
        }
        result.put("x",realX);
        result.put("y",y);
        return result;
    }

    // 审核通过
    @Override
    public void audit(ShopAuditLog shopAuditLog) {
        if (shopAuditLog.getType() == 1){
            Shop shop = new Shop();
            // 更改State店铺状态为1，审核通过
            shop.setState(1);
            // 将店铺状态更新
            shopMapper.update(shop);
            // 添加审核人id
            shopAuditLog.setAuditId(123L);
            // 添加店铺日志
            auditLogMapper.add(shopAuditLog);
            // 发送邮件
            // 1.创建复杂邮件对象
            MimeMessage mimeMessage = sender.createMimeMessage();
            // 2.发送复杂邮件的工具类
            MimeMessageHelper helper = null;
            try {
                helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
                helper.setFrom("wang155775@qq.com");
                helper.setSubject("宠物直接审核结果通知");
                // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
                helper.setText("<h1>恭喜您审核您审核通过，点击下方链接激活店铺</h1>"+
                        "http://localhost:8080/shop/active/"+shopAuditLog.getShopId(),true);
                helper.setTo("wang155775@qq.com");
            } catch (Exception e){
                throw new BussinessException("发送邮件错误！");
            }
            sender.send(mimeMessage);
        }
        if (shopAuditLog.getType() == -1){
            Shop shop = new Shop();
            // 更改State店铺状态为-1，驳回
            shop.setState(-1);
            // 将店铺状态更新
            shopMapper.update(shop);
            // 添加审核人id
            shopAuditLog.setAuditId(123L);
            // 添加店铺日志
            auditLogMapper.add(shopAuditLog);
            // 发送邮件
            // 1.创建复杂邮件对象
            MimeMessage mimeMessage = sender.createMimeMessage();
            // 2.发送复杂邮件的工具类
            MimeMessageHelper helper = null;
            try {
                helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
                helper.setFrom("wang155775@qq.com");
                helper.setSubject("宠物直接审核结果通知");
                // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
                helper.setText("<h1>抱歉！您的提交的资料未通过，点击下方链接进行处理</h1>"+
                        "http://localhost:8081/#/registerAgain?ShopId="+shopAuditLog.getShopId(),true);
                helper.setTo("wang155775@qq.com");
            } catch (Exception e){
                throw new BussinessException("发送邮件错误！");
            }
            sender.send(mimeMessage);
        }
    }

//    @Override
//    public void reject(ShopAuditLog shopAuditLog) {
//        Shop shop = new Shop();
//        // 更改State店铺状态为-1，驳回
//        shop.setState(-1);
//        // 将店铺状态更新
//        shopMapper.update(shop);
//        // 添加审核人id
//        shopAuditLog.setAuditId(123L);
//        // 添加店铺日志
//        auditLogMapper.add(shopAuditLog);
//        // 发送邮件
//        // 1.创建复杂邮件对象
//        MimeMessage mimeMessage = sender.createMimeMessage();
//        // 2.发送复杂邮件的工具类
//        MimeMessageHelper helper = null;
//        try {
//            helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
//            helper.setFrom("wang155775@qq.com");
//            helper.setSubject("宠物直接审核结果通知");
//            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
//            helper.setText("<h1>抱歉！您的提交的资料未通过，点击下方链接进行处理</h1>"+
//                    "http://localhost:8080/shop/active/"+shopAuditLog.getShopId(),true);
//            helper.setTo("wang155775@qq.com");
//        } catch (Exception e){
//            throw new BussinessException("发送邮件错误！");
//        }
//        sender.send(mimeMessage);
//    }


    // 校验方法
    private Employee verify(Shop shop, Employee admin) {
        if (StringUtils.isBlank(shop.getName())){
            throw new BussinessException("店铺名不能为空！");
        }
        // 校验两次密码是否一致
        if(!admin.getPassword().equals((admin.getComfirmPassword()))){
            throw new BussinessException("两次的密码不一致！");
        }
        // AI验证
        if(!BaiduAuditUtils.TextCensor(shop.getName())){
            throw new BussinessException("店铺名称不合规!");
        }
        if (!BaiduAuditUtils.ImgCensor(shop.getLogo())){
            throw new BussinessException("店铺logo不合规！");
        }
        // 通过findByName方法传入shop.getName()前端传递的店铺名判断店铺是否存在
        Shop tmpShop = shopMapper.findByName(shop.getName());
        if(null != tmpShop){
            throw new BussinessException("店铺已经存在！");
        }
        // 管理员对象getUsername()方法获取到管理员名字，传入员工表findByName通过传入名字查询员工是否存在
        // 当前管理员是否管理了其他店铺
        Employee employee = employeeMapper.findByName(admin.getUsername());
        // 如果当前的这个管理员对象不是null并且他里面的店铺id也不是null
        if(null != employee && null != employee.getShopId()){
            // 店铺通过id查询的方法findById传入员工表里面的店铺id得到一个店铺对象
            Shop shopById = shopMapper.findById(employee.getShopId());
            // 如果通过店铺对象获取到的管理员id和员工表里面的id相等,就证明该员工已经管理过店铺了
            if(shopById.getAdminId().equals(employee.getId())){
                throw new BussinessException("当前管理员已经关联了店铺了！");
            }
        }
        return employee;
    }
}
